<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px" style="display: flex; flex-wrap: wrap; align-items: center;">
      <el-form-item label="实验场景名称" prop="scenarioName" style="margin-right: 10px; width: 200px;">
        <el-input
            v-model="queryParams.scenarioName"
            placeholder="请输入实验场景名称"
            clearable
            @keyup.enter="handleQuery"
            style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="版本号" prop="version" style="margin-right: 10px; width: 200px;">
        <el-input
            v-model="queryParams.version"
            placeholder="请输入版本号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类" prop="category" style="margin-right: 10px; width: 200px;">
        <el-input
            v-model="queryParams.category"
            placeholder="请输入分类"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['Teacher:scenarios:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="scenariosList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="实验场景ID" align="center" prop="scenarioId" />
      <el-table-column label="实验场景名称" align="center" prop="scenarioName" />
      <el-table-column label="实验场景描述" align="center" prop="description" />
      <el-table-column label="版本号" align="center" prop="version" />
      <el-table-column label="实验场景文件存储路径或URI" align="center" prop="filePath" />
      <el-table-column label="分类" align="center" prop="category" />
      <el-table-column label="标签" align="center" prop="tags" />
      <el-table-column label="发布状态" align="center">
        <template #default="scope">
          <el-tag type="success">{{ scope.row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['Teacher:scenarios:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0 && !showPurchasedOnly"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
  </div>
</template>

<script setup>
import { listScenarios, getScenarios, delScenarios, addScenarios, updateScenarios,listValidPurchasedScenarios } from "@/api/Teacher/scenarios"
import { useRouter } from 'vue-router';
import { useExampleStore } from "@/stores/exampleStore.js";
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance()
const router = useRouter();
const exampleStore = useExampleStore();
const schoolId = exampleStore.getSchool;
const userids = exampleStore.userid;
console.log("学校id.........",schoolId);
console.log("用户ID......",userids)
const showPurchasedOnly = ref(false) // 控制显示模式的开关
const scenariosList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    scenarioName: null,
    description: null,
    version: null,
    filePath: null,
    category: null,
    tags: null,
    status: null
  },
  rules: {
    scenarioName: [
      { required: true, message: "实验场景名称不能为空", trigger: "blur" }
    ],
    filePath: [
      { required: true, message: "实验场景文件存储路径或URI不能为空", trigger: "blur" }
    ],
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "发布状态: 已发布, 草稿, 已归档不能为空", trigger: "change" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询实验场景信息列表 */
function getList() {
  loading.value = true
  if (showPurchasedOnly.value || schoolId.value) {
    // 查询已购买且有效的实验场景
    listValidPurchasedScenarios(schoolId).then(response => {
      let data = response.data
      // 客户端筛选
      if (queryParams.value.scenarioName) {
        data = data.filter(item => item.scenarioName.includes(queryParams.value.scenarioName))
      }
      if (queryParams.value.version) {
        data = data.filter(item => item.version.includes(queryParams.value.version))
      }
      if (queryParams.value.category) {
        data = data.filter(item => item.category.includes(queryParams.value.category))
      }
      if (queryParams.value.tags) {
        data = data.filter(item => item.tags.includes(queryParams.value.tags))
      }

      scenariosList.value = data
      total.value = scenariosList.value.length
      loading.value = false
    })
  } else {
    // 原有查询所有实验场景的逻辑
    listScenarios(queryParams.value, userids)
        .then(response => {
          // 检查返回的数据是否包含优惠券错误消息
          if (response.msg && response.msg.includes("请先领取优惠卷")) {
            proxy.$modal.msgError(response.msg);
            scenariosList.value = [];
            total.value = 0;
          } else {
            scenariosList.value = response.rows;
            total.value = response.total;
          }
        })
        .catch(error => {
          // 处理其他错误情况
          if (error.response?.data?.msg) {
            proxy.$modal.msgError(error.response.data.msg);
          } else {
            proxy.$modal.msgError("获取实验场景列表失败");
          }
          scenariosList.value = [];
          total.value = 0;
        })
        .finally(() => {
          loading.value = false;
        });
  }
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    scenarioId: null,
    scenarioName: null,
    description: null,
    version: null,
    filePath: null,
    category: null,
    tags: null,
    createTime: null,
    status: null
  }
  proxy.resetForm("scenariosRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.scenarioId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加实验场景信息"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _scenarioId = row.scenarioId || ids.value
  getScenarios(_scenarioId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改实验场景信息"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["scenariosRef"].validate(valid => {
    if (valid) {
      if (form.value.scenarioId != null) {
        updateScenarios(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addScenarios(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _scenarioIds = row.scenarioId || ids.value
  proxy.$modal.confirm('是否确认删除实验场景信息编号为"' + _scenarioIds + '"的数据项？').then(function() {
    return delScenarios(_scenarioIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('Teacher/scenarios/export', {
    ...queryParams.value
  }, `scenarios_${new Date().getTime()}.xlsx`)
}

// 切换显示已购买/全部实验场景
function togglePurchasedOnly() {
  showPurchasedOnly.value = !showPurchasedOnly.value
  // 重置页码
  if (!showPurchasedOnly.value) {
    queryParams.value.pageNum = 1
  }
  getList()
}

getList()
</script>